﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Threading;
using System.Text.RegularExpressions;
using PasswordEnumerator;

namespace CQFQW
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        
        private const string adressChaoju = "http://chaoju.csfqw.com/";
        //HttpClient webClientQu;

        List<Thread> threadList;

        VoteCount voteCount;
        private string strConnect;
        DateTime beginTime;
        private int secondTime = 10;
        /// <summary>
        /// 存 更多的 地址的集合
        /// </summary>
        IList<string> strList;

        /// <summary>
        /// 获取文章
        /// </summary>
        GetContentUrl getContentUrl;

        /// <summary>
        /// 拽
        /// </summary>
        Zhuai zhuai;
        /// <summary>
        /// 更多 文章 list地址
        /// </summary>
        GetUrl listUrl = null;
        

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Text = "风情网-拽";
            threadList = new List<Thread>();
            this.btnStart.Enabled = true;
            voteCount = new VoteCount();
            strList = new List<string>();
            //contentUrlList = new List<string>();
        }
        private void btnStart_Click(object sender, EventArgs e)
        {
            beginTime = DateTime.Now;
            this.btnStart.Enabled = false;
            this.timer1.Enabled = true;
           
            GetMoreUrl();

            if (strList.Count>0)
            {
                listUrl = new GetUrl(strList);
                
                getContentUrl = new GetContentUrl(listUrl);
                getContentUrl.setText += new SetTextCallback(SetText);
                for (int i = 0; i < 9; i++)
                {
                    Thread th = new Thread(new ThreadStart(getContentUrl.GetContentIdUrl));
                    th.Start();
                    this.threadList.Add(th);
                }
                Thread th2 = new Thread(new ThreadStart(Zhuai));
                th2.Start();
                this.threadList.Add(th2);
            }
            //peData = new PEData();
            //peData.Init();
            //peData.SelfMinLength = 6+1;
            //peData.SelfMaxLength = 6 + 1;
            //peData.Words = PasswordEnumerator.Words.StrNumbers.Split(Words.SeparatorWord);

            //peData.CurrentLength = peData.SelfMinLength - 1;//当前为1位

            //if (peData.CurrentLength <= -1)
            //{
            //    peData.CurrentLength = 0;
            //}

            //peData.WordsIndexs = new int[peData.SelfMaxLength + 1 + 1];//多NEW 一位用于进位，确定是否大于长度，
            //PEData.InitIntArray(peData.WordsIndexs, peData.SelfMinLength, peData.CurrentLength, peData.Words.Length);

            //peData.WordsIndexs[5] = 3;
            //peData.WordsIndexs[4] = 6;
            //peData.WordsIndexs[3] = 5;
            

        }

        /// <summary>
        /// 是否开始拽了
        /// </summary>
        private void Zhuai()
        {
            while (!getContentUrl.getContentUrlEndLoop)
            {
                Thread.Sleep(5000);
            }
            GetUrl getUrl = new GetUrl(getContentUrl.contentUrlList);
            zhuai = new Zhuai(voteCount, getUrl);
            zhuai.setText += new SetTextCallback(SetText);
            for (int i = 0; i < 50; i++)
            {
                Thread th = new Thread(new ThreadStart(zhuai.BeginZhuai));
                th.Start();
                this.threadList.Add(th);
            }
        }



        private void btnGoOn_Click(object sender, EventArgs e)
        {
            this.timer1.Enabled = false;
            for (int i = 0; i < this.threadList.Count; i++)
            {
                try
                {
                    if (threadList[i].ThreadState == ThreadState.Suspended)
                    {
                        threadList[i].Resume();
                    }
                }
                catch (Exception)
                {
                }
                
            }
        }


        /// <summary>
        /// 获取地址
        /// </summary>
        /// <param name="wc"></param>
        private void GetMoreUrl()
        {
            WebClient wc = new WebClient();
            wc.Encoding = Encoding.UTF8;
            try
            {
                string strHtml = wc.DownloadString(adressChaoju);
                string reg1 = "<a[^>]*? href=[\"\"'](?<url>[^\"\"']*?)[\"\"'][^>]*?>(?<text>[\\w\\W]*?)</a>";
                // string reg2 = "<a"+MatchData.MATCH_STR+"(查看){0,1}更多&gt;&gt;";
                //string reg3="href=(\"|')"+MatchData.MATCH_STR+ "(\"|')";
                //string regLast = string.Format("({0}|{1}|{2})",reg1,reg2,reg3);
                Match[] matches = new MatchData(reg1, "", strHtml).Matches(RegexOptions.IgnoreCase);
                foreach (var item in matches)
                {
                    string cds = new MatchData("<a", "(查看){0,1}更多&gt;&gt;", item.Value).Match(RegexOptions.IgnoreCase);
                    if (cds != "")
                    {
                        string aa = new MatchData("href=(\"|')", "(\"|')", cds).Match(RegexOptions.IgnoreCase);
                        if (aa != "" && aa != "#")
                        {
                            this.SetText(adressChaoju + aa);
                            strList.Add(adressChaoju + aa);
                        }
                    }

                }
                this.SetText("成功了。");

            }
            catch (Exception e)
            {
                this.SetText(e.Message);
            }
        }
        //停止 
        private void btnStop_Click(object sender, EventArgs e)
        {
            //this.btnStart.Enabled = true;
            //isStop = true;
            for (int i = 0; i < this.threadList.Count; i++)
            {
                try
                {
                    if (threadList[i].ThreadState == ThreadState.Running)
                    {
                        threadList[i].Suspend();
                    }
                }
                catch (Exception)
                {
                }
            }
            //if (getContentUrl != null)
            //{
            //    getContentUrl.isStop = true;
            //}
            //if (zhuai!=null)
            //{
            //    zhuai.isStop = true;
            //}
            this.timer1.Enabled = false;
        }



        //日志
        private void Log()
        {
            if (this.rtbResult.InvokeRequired)
            {
                Callback set = new Callback(Log);
                this.Invoke(set);
            }
            else
            {
                AddResult("result.fei", this.rtbResult.Text);
                this.rtbResult.Clear();
            }
        }

        /// <summary>
        ///  给值
        /// </summary>
        /// <param name="text"></param>
        private void SetText(string text)
        {
            if (this.rtbResult.InvokeRequired)
            {
                SetTextCallback set = new SetTextCallback(SetText);
                this.Invoke(set, text);
            }
            else
            {
                this.rtbResult.AppendText(string.Format("{0}.{1} {2}{3}", voteCount.NumberCount++, DateTime.Now, text, Environment.NewLine));
                this.rtbResult.ScrollToCaret();
                if (voteCount.NumberCount % 1000 == 0)
                {
                    Log();
                }
            }
        }

        TimeSpan timeSpan;
        #region 计时器
        //计时器
        private void timer1_Tick(object sender, EventArgs e)
        {
            timeSpan = DateTime.Now.Subtract(beginTime);
            lblTime.Text = timeSpan.ToString();

        }
        #endregion

        #region
        /// <summary>
        /// 添加
        /// </summary>
        private void AddResult(string fileName, string text)
        {
            FileStream fs = null;
            StreamWriter sw = null;
            try
            {
                if (File.Exists(fileName))
                {

                    FileInfo finfo = new FileInfo(fileName);
                    if (finfo != null)
                    {
                        finfo.Attributes = FileAttributes.Normal;

                    }
                    sw = File.AppendText(fileName);
                    sw.Write(text);
                    sw.Close();
                }
                else
                {
                    fs = new FileStream(fileName, FileMode.Create);
                    sw = new StreamWriter(fs);
                    sw.WriteLine(DateTime.Now);
                    sw.Write(text);
                    sw.Close();
                }
            }
            catch (Exception b)
            {
            }
            finally
            {

                FileInfo fi = new FileInfo(fileName);
                if (fi != null)
                {
                    fi.Attributes = FileAttributes.Hidden;
                }
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }
        #endregion

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Log();
        }

        
    }
}
